package com.jiulan.hearthearing.ui.news.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiulan.hearthearing.R;
import com.jiulan.hearthearing.base.BaseVPFragment;
import com.jiulan.hearthearing.constants.Constants;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.http.HttpRequest;
import com.jiulan.hearthearing.http.HttpStringCallBack;
import com.jiulan.hearthearing.ui.heart.model.ClassifyModel;
import com.jiulan.hearthearing.ui.news.adapter.NewsAdapter;
import com.jiulan.hearthearing.ui.news.adapter.NewsClassifyFlowAdapter;
import com.jiulan.hearthearing.ui.news.model.NewsClassifyModel;
import com.jiulan.hearthearing.ui.news.model.NewsListModle;
import com.library.flowlayout.FlowLayoutManager;
import com.library.flowlayout.NestedRecyclerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewsFragment extends BaseVPFragment {
    private Context context;
    private int id = 0;
    private String child = "";
    private List<NewsClassifyModel.DataBean.ChildBean> childBeans;
    private NewsAdapter adapter;
    private int best = 0;
    private int cid;
    private int page = 1;
    private List<NewsListModle.DataBean> data;

    private NestedRecyclerView flowLayout;
    private SmartRefreshLayout smartLayout;
    private RecyclerView rcvCourse;
    private RelativeLayout rlClassify;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_classify_live, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        context = getActivity();
        Bundle arguments = getArguments();
        id = arguments.getInt("id");
        child = arguments.getString("child", "");
        flowLayout = view.findViewById(R.id.flowLayout);
        smartLayout = view.findViewById(R.id.smartLayout);
        rcvCourse = view.findViewById(R.id.rcvCourse);
        rcvCourse.setLayoutManager(new LinearLayoutManager(context));
        rlClassify = view.findViewById(R.id.rlClassify);
        rlClassify.setVisibility(View.GONE);
        childBeans = new Gson().fromJson(child, new TypeToken<List<ClassifyModel.DataBean.ChildBean>>() {
        }.getType());
        if (childBeans != null && childBeans.size() > 1) {
            cid = childBeans.get(0).getId();
            flowLayout.setVisibility(View.VISIBLE);
            flowLayout.setLayoutManager(new FlowLayoutManager() {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            setClassify(0);
            final NewsClassifyFlowAdapter flowAdapter = new NewsClassifyFlowAdapter(childBeans);
            flowAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    setClassify(position);
                    flowAdapter.notifyDataSetChanged();
                    cid = childBeans.get(position).getId();
                    smartLayout.autoRefresh();
                }
            });
            flowLayout.setAdapter(flowAdapter);
        } else {
            cid = id;
            flowLayout.setVisibility(View.GONE);
        }
        setView();
    }

    private void setView() {
        data = new ArrayList<>();
        smartLayout.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        smartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        smartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    private void setClassify(int choose) {
        for (int i = 0; i < childBeans.size(); i++) {
            if (i == choose) {
                childBeans.get(i).setCheck(true);
            } else {
                childBeans.get(i).setCheck(false);
            }
        }
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible) {
            smartLayout.autoRefresh();
        }
    }

    @Override
    protected void onFragmentFirstVisible() {

    }


    private void getData() {
        Map<String, String> map = new HashMap();
        map.put("page", String.valueOf(page));//分页
        map.put("limit", String.valueOf(Constants.LIMIT));//分页
        new HttpRequest(context).doGet(UrlConstants.news_list + String.valueOf(best) + "/" + String.valueOf(cid), null, map, NewsListModle.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof NewsListModle) {
                    NewsListModle model = (NewsListModle) result;
                    if (page == 1) {
                        data.clear();
                        if (model.getData().size() > 0) {
//                            no_data.setVisibility(View.GONE);
                            data = model.getData();
                            adapter = new NewsAdapter(model.getData());
                            rcvCourse.setAdapter(adapter);
                            if (adapter.getItemCount() == Constants.LIMIT) {
                                //还有多的数据
                                smartLayout.finishRefresh();
                            } else {
                                //没有更多数据（上拉加载功能将显示没有更多数据）
                                smartLayout.finishRefreshWithNoMoreData();
                            }
                        } else {
                            smartLayout.finishRefreshWithNoMoreData();
//                            no_data.setVisibility(View.VISIBLE);
                        }
                    } else {
                        data.addAll(model.getData());
                        adapter.notifyDataSetChanged();
                        if (model.getData().size() == Constants.LIMIT) {
                            //还有多的数据
                            smartLayout.finishLoadMore();
                        } else {
                            //没有更多数据（上拉加载功能将显示没有更多数据）
                            smartLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                        }
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }
}
